package kassiopeia.agent.infrastructure;

import kassiopeia.plugin.Event;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class EventDistributionService {

    private static final Logger logger = Logger.getLogger(EventDistributionService.class);

    @Autowired
    private AliveAgentsHolder aliveAgentsHolder;

    @Autowired
    private HashProvider hashProvider;

    @Value("${kassiopeia.agent.id}")
    private String thisAgentId;

    public String findResponsibleAgent(Event event) {

        String nearestAgentId = thisAgentId;
        long nearestAgentHash = hashProvider.getAgentHash(thisAgentId);

        long eventHash = hashProvider.getEventHash(event);

        for(String agentId : aliveAgentsHolder.getAliveAgentsIds()) {
            long agentHash = hashProvider.getAgentHash(agentId);

            if(Math.abs(agentHash-eventHash) < Math.abs(nearestAgentHash-eventHash)) {
                nearestAgentId = agentId;
                nearestAgentHash = agentHash;
            }
        }

        logger.debug("Agent responsible for event: " + event + " has ID: " + nearestAgentId);

        return nearestAgentId;
    }

    public AliveAgentsHolder getAliveAgentsHolder() {
        return aliveAgentsHolder;
    }

    public void setAliveAgentsHolder(AliveAgentsHolder aliveAgentsHolder) {
        this.aliveAgentsHolder = aliveAgentsHolder;
    }

    public HashProvider getHashProvider() {
        return hashProvider;
    }

    public void setHashProvider(HashProvider hashProvider) {
        this.hashProvider = hashProvider;
    }

    public String getThisAgentId() {
        return thisAgentId;
    }

    public void setThisAgentId(String thisAgentId) {
        this.thisAgentId = thisAgentId;
    }
}
